(function(layui, window, document) {
  'use strict';

  layui = layui && layui.hasOwnProperty('default') ? layui['default'] : layui;

  var MODULE_NAME = 'pagetabs';

  var ClassName = {
    SHOW        : 'layui-show',
    THIS        : 'layui-this',
    CONTEXT_MENU: 'layadmin-pagetabs-contextmenu',
    BACKDROP    : 'layadmin-pagetabs-backdrop'
  };

  layui.define(['jquery', 'element', 'setter', 'view', 'ClipboardJS'], function(exports) {
    var $ = layui.jquery;
    var element = layui.element;
    var setter = layui.setter;
    var view = layui.view;
    var hint = layui.hint();

    var $win = $(window);
    var $body = $('body');

    var PageTabs = function() {
      this.id = null;
      this.LAY_FILTER = ''; // 过滤器

      this.curr = {};
      this.$elem = null;
    };

    PageTabs.prototype.render = function(id) {
      this.$elem = $('#' + id);

      if (this.$elem.length <= 0) return;

      this.id = id;
      this.LAY_FILTER = this.$elem.attr('lay-filter');

      var _this = this;
      var $tabs = this.$elem.find('.layui-tab-title>li');

      $tabs.each(function(index) {
        var $this = $(this);
        if ($this.hasClass(ClassName.THIS)) {
          _this.current = { index: index, id: $this.attr('lay-id'), attr: $this.attr('lay-attr') };
          return false;
        }
      });

      this.$backdrop = this.getBackdrop();

      return this;
    };

    PageTabs.prototype._bindEvents = function() {
      var _this = this;
      var $target;
      var Events = {
        CLOSE_THIS_TAB: function() {
          _this.closeThisTab($(this).attr('lay-id'));
        },
        CLOSE_OTHER_TABS: function() {
          _this.closeOtherTabs('other', $(this).attr('lay-id'));
        },
        CLOSE_ALL_TABS: function() {
          _this.closeAllTabs();
        },
        REFRESH_THIS_TAB: function() {
          var $frame = _this.$elem.children('.layui-tab-content>.' + ClassName.SHOW + '>iframe');
          $frame[0] && $frame[0].currentWindow.location.reload(true);
        },
        OPEN_NEW_WINDOW: function() {
          window.open();
        }
      };

      $body.on('contextmenu.' + MODULE_NAME, '#' + this.id + '>.layui-tab-title>li', function(e) {
        e.preventDefault();

        var $this = $(this);
        var path  = $this.attr('lay-attr');
        var lock  = $.type($this.attr('lay-lock')) === 'string';

        var winWidth = $win.width();
        var mousePoint = e.clientX;

        $('#' + ClassName.CONTEXT_MENU).remove();

        var $menu = $([
          '<ul class="' + ClassName.CONTEXT_MENU + '" id="' + ClassName.CONTEXT_MENU + '" lay-id="' + currentLayId + '">',
          '<li layadmin-pagetabs-event="REFRESH_THIS_TAB"><a href="javascript:;">刷新</a></li>',
          lock ? '' : '<li layadmin-pagetabs-event="CLOSE_THIS_TAB"><a href="javascript:;">关闭</a></li>',
          '<li layadmin-pagetabs-event="CLOSE_OTHER_TABS"><a href="javascript:;">关闭其他</a></li>',
          '<li layadmin-pagetabs-event="CLOSE_ALL_TABS"><a href="javascript:;">全部关闭</a></li>',
          '<hr>',
          '<li layadmin-pagetabs-event="copyPath" data-clipboard-text="' + path + '"><a href="javascript:;">复制路径</a></li>',
          '<li layadmin-pagetabs-event="OPEN_NEW_WINDOW"><a href="javascript:;">新窗口</a></li>',
          '</ul>'
        ].join(''));

        var $backdrop = $(Selector.BACKDROP);

        if ($backdrop.length <= 0) {
          $backdrop = $('<div id="' + ClassName.BACKDROP + '" layadmin-pagetabs-event="closeContextMenu" />');
          $backdrop.css({
            position: 'fixed',
            top     : 0,
            right   : 0,
            bottom  : 0,
            left    : 0,
            zIndex  : 20000,
            opacity : 0,
            display : 'none'
          });
          $body.append($backdrop);
        }

        $menu.on('contextmenu', function(e) {
          e.preventDefault();
        });

        $menu.on('click.' + MODULE_NAME, 'li', function() {
          var $this = $(this);
          var eventName = $this.attr('layadmin-pagetabs-event');
          $.isFunction(Events[eventName]) && Events[eventName].call(this);
          _this.closeContextmenu();
        });

        $menu.css({
          top : e.clientY + 'px',
          left: ((winWidth - mousePoint < 105) ? (winWidth - 105) : mousePoint) + 'px'
        });

        $body.append($menu);
        $backdrop.show();
      });
    };

    PageTabs.prototype.closeContextmenu = function() {
      this.$contextmenu && this.$contextmenu.remove();
      this.$backdrop && this.$backdrop.hide();
      this.$content = null;
    };

    PageTabs.prototype.closeThisTab = PageTabs.prototype.close = function(layId) {
      element.tabDelete(this.LAY_FILTER, layId);
    };

    PageTabs.prototype.refreshThisTab = PageTabs.prototype.refresh = function(showWarning) {
      // !showWarning && console.warn('[pagetabs] 此方法会使页面全部刷新，除非必要，请尽量局部刷新');

      // var thisTab = this.getCurrentInfo();
      // this.close(thisTab.id).add(thisTab);

      // return this;

      if (this.$elem.length <= 0) return;

      var $frame = this.$elem.children('.layui-tab-content>.' + ClassName.SHOW + '>iframe');
      $frame[0] && $frame[0].currentWindow.location.reload(true);
    };

    PageTabs.prototype.closeOtherTabs = function(type, targetId) {
      if (this.$elem.length <= 0) return;

      var _this = this;
      var $tabs = this.$elem.children('.layui-tab-title>li:gt(0)');

      $tabs.each(function() {
        var layId = $(this).attr('lay-id');
        (type === 'all' || layId !== targetId) && element.tabDelete(_this.LAY_FILTER, layId);
      });

      this.closeContextmenu();
    };

    PageTabs.prototype.closeAllTabs = function() {
      this.closeOtherTabs('all');
    };

    PageTabs.prototype.copyPath = function(layId) {
      new layui.ClipboardJS();
    };

    PageTabs.prototype.openNewWindow = function() {
      var $tab = this.$elem.children('.layui-tab-title>li[lay-id="' + this.LAY_ID + '"]');
      var path = $tab.attr('lay-attr');
      path && window.open(path);
    };

    PageTabs.prototype.getCurrentId = function() {
      return this.cache.$head.find('.' + ClassName.THIS).attr('lay-id');
    };

    PageTabs.prototype.add = function(/* { url, id, text, tip } */) {
      if (this.$elem.length <= 0) return;

      var l = arguments.length;
      var url = l > 0 ? arguments[0] : '';
      var id = l > 1 ? arguments[1] : '';
      var label = l > 2 ? arguments[2] : '';
      var tip = l > 3 ? arguments[3] : '';

      var matchTo;
      var _this = this;
      var $tabs = this.$elem.find('.layui-tab-title > li');
      $tabs.each(function(index) {
        var layId = $(this).attr('lay-id');

        if (layId === url) {
          matchTo = true;
          _this.curr.index = index;
          _this.curr.id = option || option.url;
        }
      });

      if (setter.pagetabs) {
        if (!matchTo) {
          element.tabAdd(FILTER_PAGETABS, {
            title  : '<span title="' + option.tip + '">' + option.text + '</span>',
            id     : option.id || option.url,
            url    : option.url,
            attr   : option.id || option.url,
            content: '<iframe src="' + option.url + '" class="layadmin-iframe" name="' + option.id + '" data-id="' + option.id + '" allowfullscreen="true" frameborder="no"></iframe>'
          });
          admin.tabsPage.index = $tabs.length;
          admin.tabsPage.id = option.id || option.url;
        }
      } else {
        var $frame = admin.pagetabsBody(admin.pagetabs.index).find('iframe');
        $frame[0].contentWindow.location.href = option.url;
      }

      // 定位当前tabs
      element.tabChange(FILTER_PAGETABS, option.id || option.url);
    };

    PageTabs.prototype.add = function(option /* { url, id, text, tip } */) {
      if (typeof option !== 'object') hint('期待"Object"类型参数，但是检测到类型是' + typeof option);

      var filter = this.cache.filter;
      var $body = this.cache.$body;
      var showLoad = this.cache.showLoad;
      var tabIndex = this.exist(option.id);

      var getAbsoluteUrl = function(url) {
        return url.indexOf($$path) === -1 ? $$path + (App.util.beginWith(url, '/') ? '' : '/') + url : url;
      };

      option.url = option.url ? getAbsoluteUrl(option.url) : '#';

      if (tabIndex === -1) {
        var loadIndex = -1;
        if (showLoad) {
          loadIndex = layer.load(2, { time: 10 * 1000 }); // 10s 后关闭
        }

        var content = '<iframe src="' + option.url + '" name="' + option.id + '" data-id="' + option.id + '" frameBorder="no" border="0"></iframe>';
        var text = '<span title="' + (option.tip ? option.tip : option.text) + '">' + option.text + '</span>';

        element.tabAdd(filter, { title: text, content: content, id: option.id });
        $body.find('iframe[data-id=' + option.id + ']').on('load', function() {
          showLoad && layer.close(loadIndex);
        });

        // var timer = setTimeout(function() {
        //   showLoad && layer.close(loadIndex)
        //   clearTimeout(timer)
        // }, 10 * 1000) // 理论使用 layui.setter.request.timeout 的配置，但是各种原因直接写死
      }
      // 重新设置一些配置
      this.change(option.id);
      this._setContextmenu();
      return this;
    };
    //
    PageTabs.prototype.change = function(id) {
      id && element.tabChange(this.cache.filter, id);
      return this;
    };

    PageTabs.prototype.getCurrentInfo = function() {
      if (this.$elem.length <= 0) return;

      var $title = this.$elem.children('.layui-tab-title');
      var $content = this.$elem.children('.layui-tab-content');

      var ret = {};

      var $headText = $title.find('.' + ClassName.THIS).find('span');
      var $bodyFrame = $content.find('.' + ClassName.SHOW).find('iframe');

      if ($headText.length !== 1 || $bodyFrame.length !== 1) {
        hint('无法确定获取当前选项卡');
      } else {
        ret = {
          url : $bodyFrame.attr('src'),
          id  : $bodyFrame.attr('data-id'),
          text: $headText.text(),
          tip : $headText.attr('title')
        };
      }

      return ret;
    };

    exports(MODULE_NAME, new PageTabs());
  });
// eslint-disable-next-line no-undef
})(layui, window, document);
